package lucendoc;

import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.util.Date;

import org.apache.lucene.analysis.standard.StandardAnalyzer;
import org.apache.lucene.document.Document;
import org.apache.lucene.document.Field;
import org.apache.lucene.index.IndexWriter;
import org.apache.lucene.store.Directory;
import org.apache.lucene.store.FSDirectory;
import org.apache.lucene.util.Version;
import org.apache.poi.hwpf.extractor.WordExtractor;


public class IndexaDoc {
  public IndexaDoc() {
   try{
	    File indexDir = new File("c:\\indexdir");
	    File dataDir = new File("d:\\temp2");
	    long start = new Date().getTime();
	    int numIndexed = index(indexDir, dataDir);
	    long end = new Date().getTime();
	    System.out.println("Se han indizado " + numIndexed + " archivos          en " + (end - start) + " milisegundos");
   }
   catch(Exception err){}
  }
  public static int index(File indexDir, File dataDir)
    throws IOException {
    if (!dataDir.exists() || !dataDir.isDirectory()) {
      throw new IOException(dataDir
        + " no existe o no es un directorio ");
    }
    Directory directory = FSDirectory.open(indexDir);
    borrarDirectorio(indexDir);
    
    IndexWriter writer = new IndexWriter(directory, new StandardAnalyzer(Version.LUCENE_30), IndexWriter.MaxFieldLength.LIMITED);
    writer.setUseCompoundFile(false);
    indexDirectory(writer, dataDir);
    int numIndexed = writer.numDocs();
    writer.optimize();
    directory.close();
    writer.close();
    return numIndexed;
  }
  
  private static void borrarDirectorio(File dir){
	  File[] ficheros = dir.listFiles();
	  for (int x=0;x<ficheros.length;x++){
		  if (ficheros[x].isDirectory()) {
			  System.out.print("Borrando: "+ficheros[x]);
			  borrarDirectorio(ficheros[x]);
			}
		  System.out.print("Borrando: "+ficheros[x]);
		  ficheros[x].delete();
	  }
  }
  
  private static void indexDirectory(IndexWriter writer, File dir)
    throws IOException {
    File[] files = dir.listFiles();
    for (int i = 0; i < files.length; i++) {
      File f = files[i];
      if (f.isDirectory()) {
        indexDirectory(writer, f);  // recurse
      } else if (f.getName().endsWith(".doc")) {
        indexFile(writer, f);
      }
    }
  }
  
  private static void indexFile(IndexWriter writer, File f)
    throws IOException {
	  try{
		    if (f.isHidden() || !f.exists() || !f.canRead()) {
		      return;
		    }
		    System.out.println("Indizando " + f.getCanonicalPath());
		    Document doc = new Document();
		    doc.add(new Field("filename", f.getCanonicalPath(), Field.Store.YES, Field.Index.ANALYZED));
		    
		    WordExtractor we = new WordExtractor(new FileInputStream(f));
		    doc.add(new Field("Contenido", we.getText(),Field.Store.YES, Field.Index.ANALYZED ));
		    if (we.getSummaryInformation().getAuthor() == null){
			       doc.add(new Field("Autor","Sin Autor", Field.Store.YES, Field.Index.ANALYZED));
			}
			else{
			        doc.add(new Field("Autor", we.getSummaryInformation().getAuthor(), Field.Store.YES, Field.Index.ANALYZED) );
			}
		    if (we.getSummaryInformation().getCreateDateTime().toLocaleString().substring(0,10) == null){
			       doc.add(new Field("Fecha","Sin fecha", Field.Store.YES, Field.Index.ANALYZED));
			}
			else{
				doc.add(new Field("Fecha", we.getSummaryInformation().getCreateDateTime().toLocaleString().substring(0,10), Field.Store.YES, Field.Index.ANALYZED) );
			}
		    doc.add(new Field("Tipo", "doc", Field.Store.YES, Field.Index.ANALYZED));
		    /*
		    String titulo = we.getSummaryInformation().getTitle();
		
		    if (titulo!= null){
		       doc.add(Field.Text("Titulo", we.getSummaryInformation().getTitle()) );
		    }
		    else{
		    	doc.add(Field.Text("Titulo", "Sin titulo" ) );
		    }
		    */
		    
		    System.out.println(we.getSummaryInformation().getAuthor());
		    writer.addDocument(doc);
		    writer.optimize();
		    writer.commit();
	  }
	  catch(Exception err){
		  System.out.println("Error: "+err);
	  }
  }
}
